<template>
  <!-- 照片上传 -->
  <div :class="{ 'Uploab-box': fileList.length > 0 }">
    <!-- 上传的框框 -->
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :http-request="succesFn"
      :limit="100"
      :on-remove="onRemove"
    >
      <slot>
        <i class="el-icon-plus" />
        <span
          class="el-upload-list__item-delete"
          @click="onRemove"
        >
          <i class="el-icon-delete"></i>
        </span>
      </slot></el-upload>
    <!-- 上传进度条 -->
    <el-progress
      v-show="fileList.length > 0 && percent !== 100"
      :text-inside="true"
      :stroke-width="24"
      :percentage="percent"
      status="success"
    />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDTn5EBvUoMn0znQq1xf8QUJuIUTEk38yb',
  SecretKey: 'A91jFD3lKhssgHeqoY7RWO9qKZcS4QZW'
})
export default {
  data() {
    return {
      fileList: [],
      percent: 0 // 上传进度条
    }
  },
  methods: {
    // 删除头像
    onRemove() {
      this.fileList = []
    },

    // 上传头像
    succesFn(res) {
      this.fileList.push({ url: '' })
      // console.log(res)
      // res 就是我们上传的图片对象
      //  我们上传给后端的对象是res.file
      cos.putObject(
        {
          Bucket: 'hr-vue-1312874545' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() /* 必须 上传的文件名 字符串类型  */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(JSON.stringify(progressData), 49)
            this.percent = progressData.percent * 100
          }
        },
        (err, data) => {
          console.log(err || data)

          this.fileList[0].url = 'http://' + data.Location
          // console.log(this.fileList[0].url, '上传成功后返回的腾讯地址')
        }
      )
    }
  }
}
</script>

<style lang='scss' scoped>
.Uploab-box {
  width: 145px;
  .el-upload--picture-card {
    display: none;
  }
}
</style>
<style scoped>
.el-progress {
  width: 100%;
}
</style>
